package com.example.user.service;

import com.example.common.Ov.QuotaApplicationOv;
import com.example.common.Ov.UserOv;
import com.example.common.entity.Rsp;
import com.example.common.pojo.Quota;
import com.example.common.pojo.QuotaApplication;
import com.example.user.mapper.QuotaApplicationMapper;
import com.example.user.mapper.QuotaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuotaServiceImpl implements QuotaService {

    @Autowired
    QuotaMapper quotaMapper;

    @Autowired
    QuotaApplicationMapper quotaApplicationMapper;

    //获取额度列表
    @Override
    public Rsp geQuotatList() {
        List<Quota> quotaList = quotaMapper.getList();
//        List<String> list = new ArrayList<>();
//        for (Quota q:quotaList) {
//            list.add(q.getQuotaType()+" ["+q.getQuota().toString().substring(0,q.getQuota().toString().indexOf("."))+"]");
//        }
        return new Rsp(0,quotaList,"获取成功");
    }

    //申请额度
    @Override
    public Rsp quotaApp(UserOv userOv,QuotaApplicationOv quotaApplicationOv) {
        //首先查询是否有额度正在申请中
        QuotaApplication quotaApplication = new QuotaApplication();
        quotaApplication.setUserId(userOv.getId());
        quotaApplication.setStatus("0");
        QuotaApplication quotaApp = quotaApplicationMapper.getByUserIdAndStatus(quotaApplication);
        if(!StringUtils.isEmpty(quotaApp)){
            //有额度申请请求，不能再申请
            return new Rsp(0,"已有额度在申请当中");
        }

        Quota quota = new Quota();
        String qt = quotaApplicationOv.getQuotaType();
        quota.setQuotaType(qt.substring(0,qt.indexOf("[")));
        //条件查询额度
        Quota q1 = quotaMapper.getByCondition(quota);
        if(StringUtils.isEmpty(q1)){
            //暂无该额度申请
            return new Rsp(0,"暂无该额度申请");
        }
        QuotaApplication qq = new QuotaApplication();
        qq.setQuotaId(q1.getId());
        qq.setQuotaData(quotaApplicationOv.getQuotaData());
        qq.setQuotaImage(quotaApplicationOv.getQuotaImage());
        qq.setUserId(userOv.getId());
        int result = quotaApplicationMapper.insertSelective(qq);
        return result>0?new Rsp(0,"申请成功"):new Rsp(0,"申请失败");
    }
}
